<?php

defined('BASEPATH') OR exit('No direct script access allowed');


if ( ! function_exists('splitTable'))
{
	function splitTable($table, $data, $mod=10)
	{
		$w = strlen(floor($mod));
		$d = "%0".$w."d";
		$mod = $data%$mod;
		$var=sprintf($d, $mod);
		return $table.$var;
	}
}

/**
 * 去除多余的0
 */
if ( ! function_exists('del0'))
{
	function del0($s)
	{
		$s = trim(strval($s));
		if (preg_match('#^-?\d+?\.0+$#', $s)) {
			return preg_replace('#^(-?\d+?)\.0+$#','$1',$s);
		}
		if (preg_match('#^-?\d+?\.[0-9]+?0+$#', $s)) {
			return preg_replace('#^(-?\d+\.[0-9]+?)0+$#','$1',$s);
		}
		return $s;
	}
}

/**
 * Json 返回处理
 */
if ( ! function_exists('jsonReturn'))
{
	function jsonReturn($errno, $msg = NULL, array $data=array(),$return=false)
	{
		$json = array(
			'errno' => $errno,
			'msg' => $msg
		);
		if(!empty($data)) $json['data'] = $data;
		if($return){
			return json_encode($json);
		}else{
			die(json_encode($json));
		}
		
	}
}

/**
 * 检查国别码是否存在
 */
if ( ! function_exists('checkArea'))
{
	function checkAreaisExists($area)
	{
		$areaList = array('86'=>'China');
		return array_key_exists($area, $areaList);
	}
}

if ( ! function_exists('curl_get'))
{
	function curl_get($url,$data = array()) {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //不直接显示回传结果
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		if(!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		$rs = curl_exec($curl);
		curl_close($curl);
		return $rs;
	}
}

/**
 * 是否是ios
 */
if ( ! function_exists('isIOS'))
{
	function isIOS()
	{
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
		 	return true;
		}else{
			return false;
		}
	}
}

if ( ! function_exists('curl_get'))
{
	function curl_get($url,$data = array()) {
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //不直接显示回传结果
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		if(!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		$rs = curl_exec($curl);
		curl_close($curl);
		return $rs;
	}
}



/**
 * 写记录
 * @param String/Array $params 要记录的数据
 * @param String $file 文件名.该记录会保存到 data 目录下
 * @param Int $fsize 文件大小M为单位.默认为1M
 * @param bool $only 只写一个文件
 * @return null
 */

if ( ! function_exists('writeDebug'))
{
	function writeDebug($params, $filename='debug', $fsize=1,$only=false)
	{
	    is_scalar( $params) or ($params = var_export($params, true)); //是简单数据
	    if (!$params) {
	        return false;
	    }
	    clearstatcache();
	    $dir	=	'/tmp/log/';

	    if (!$only) {
	        $date	=	date('Ymd');

	        $file 	= 	$dir . $filename.$date. '.log';
	        $size 	= 	file_exists( $file) ? @filesize( $file) : 0;
        $flag 	= 	$size < max(1, $fsize)*1024*1024; //标志是否附加文件.文件控制在1M大小
        	if (!$flag) {
            	rename($file,$dir.$filename.$date.'-'.time().".log");
        	}
    	} else {
        	$flag	=	true;
        	$file 	= 	$dir . $filename. '.log';
        	$size 	= 	file_exists( $file) ? @filesize( $file) : 0;
    	}
    	$prefix = '';
    	($size==0) && $prefix =<<<EOD
＃LOG \n
EOD;
    	@file_put_contents($file, $prefix.$params."\n", $flag ? FILE_APPEND : null);
	}

}

if ( ! function_exists('writeWXFile'))
{
	function writeWXFile($log)
	{
	    writeDebug($log, 'wechat');
	}

}

/**
 * 正则检查
 */
if ( ! function_exists('regex'))
{
	function regex($value,$rule) 
	{
        $validate = array(
            'require'		=> '/.+/',
        	'email'			=> '/[^@]+@[^@]+/i',
            'url'			=> '/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/',
            'currency'		=> '/^\d+(\.\d+)?$/',
            'number'		=> '/^\d+$/',
            'zip'			=> '/^[1-9]\d{5}$/',
            'integer'		=> '/^[-\+]?\d+$/',
            'double'		=> '/^[-\+]?\d+(\.\d+)?$/',
            'english'		=> '/^[A-Za-z]+$/',
			'invite_code'	=> '/^[0-9A-Za-z]+$/',
			'nickname'		=> '/^[0-9_A-Za-z\x{4E00}-\x{9FA5}]{2,16}$/u',
			'mobile'		=> '/^1[0-9]{10}$/',
			'qq'			=> '/^[1-9][0-9]{4,13}$/',
        	'username'		=> '/^[a-zA-Z0-9_]{6,18}$/',
			'password'		=> '/^(.){4,18}$/',
			'yidong'		=> '/^(13[4-9]|15[0|1|2|7|8|9]|18[2|3|7|8]|147)\d{8}$/',
        );
        // 检查是否有内置的正则表达式
        if(isset($validate[strtolower($rule)]))
            $rule   =   $validate[strtolower($rule)];
        return preg_match($rule,$value)===1;
    }
}

/**
 * 获取客户端IP
 */
if ( ! function_exists('get_ip'))
{
	function get_ip() 
	{
        static $ip = false;
		if ($ip !== false) return $ip;
		foreach (array('HTTP_CLIENT_IP', 'HTTP_INCAP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $aah) {
			if (!isset($_SERVER[$aah])) continue;
			$cur2ip = $_SERVER[$aah];
			$curip = explode('.', $cur2ip);
			if (count($curip) !== 4)  break; // If they've sent at least one invalid IP, break out
			foreach ($curip as $sup)
			if (($sup = intval($sup)) < 0 or $sup > 255)
				break 2;
			$curip_bin = $curip[0] << 24 | $curip[1] << 16 | $curip[2] << 8 | $curip[3];
			foreach (array(
					//hexadecimal ip  ip mask
					array(0x7F000001,     0xFFFF0000), // 127.0.*.*
					array(0x0A000000,     0xFFFF0000), // 10.0.*.*
					array(0xC0A80000,     0xFFFF0000), // 192.168.*.*
			) as $ipmask) {
				if (($curip_bin & $ipmask[1]) === ($ipmask[0] & $ipmask[1])) break 2;
			}
			return $ip = $cur2ip;
		}
		return $ip = isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:"";
    }
}

/**
 * 发送短信验证码
 */
if ( ! function_exists('sendSMS'))
{
	function sendSMS($area,$phone,$code,$tempName='normal')
	{
		require_once(APPPATH . 'config/yuntongxun.php');
		// var_dump($config);
		require_once(PUBPATH . 'third_party/yuntongxun/CCPRestSmsSDK.php');
		$rest = new REST($config['sms']['serverIP'],$config['sms']['serverPort'],$config['sms']['softVersion']);
		$rest->setAccount($config['sms']['accountSid'],$config['sms']['accountToken']);
		$rest->setAppId($config['sms']['appId']);
		$tempId = $config['sms'][$tempName];
		$params = array($code);
		if($tempName == 'normal'){
			$params = array($code,'5');
		}
		// 发送模板短信
		$result = $rest->sendTemplateSMS($phone,$params,$tempId);
		if($result == NULL ) {
			writeDebug("[".date('Y-m-d H:i:s')."] [$area]$phone".var_export($smsok),'sendSMS');
			return false;
		}
		if($result->statusCode!=0) {
		 	writeDebug("[".date('Y-m-d H:i:s')."] [$area]$phone ".$result->statusCode."=".$result->statusMsg,'sendSMS');
			return false;
		}else{
		 	// 获取返回信息
		 	$smsmessage = $result->TemplateSMS;
		 	writeDebug("[".date('Y-m-d H:i:s')."] [$area]$phone ".$smsmessage->dateCreated."=".$smsmessage->smsMessageSid,'sendSMS');
		 	return true;
		}
	}
}


/**
 *获取操作系统版本
 *
 *@return array
 */
if ( ! function_exists('getSystem'))
{
	function getSystem()
	{
		if(empty($_SERVER['HTTP_USER_AGENT'])){
	        return '未知操作系统';
	    }
	    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	    $os    = '';
	    if(strpos($agent, 'win') !== false){
	        if (strpos($agent, 'nt 5.1') !== false){
	            $os = 'Windows XP';
	        }elseif (strpos($agent, 'nt 5.2') !== false){
	            $os = 'Windows 2003';
	        }elseif (strpos($agent, 'nt 5.0') !== false){
	            $os = 'Windows 2000';
	        }elseif (strpos($agent, 'nt 6.0') !== false){
	            $os = 'Windows Vista';
	        }elseif (strpos($agent, 'nt 6.1') !== false){
	            $os = 'Windows 7';
	        }elseif (strpos($agent, 'nt 10.0') !== false){
	            $os = 'Windows 10';
	        }elseif (strpos($agent, 'nt') !== false){
	            $os = 'Windows NT';
	        }elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false){
	            $os = 'Windows ME';
	        }elseif (strpos($agent, '98') !== false){
	            $os = 'Windows 98';
	        }elseif (strpos($agent, '95') !== false){
	            $os = 'Windows 95';
	        }elseif (strpos($agent, '32') !== false){
	            $os = 'Windows 32';
	        }elseif (strpos($agent, 'ce') !== false){
	            $os = 'Windows CE';
	        }
	    }elseif (strpos($agent, 'linux') !== false){
	        $os = 'Linux';
	    }elseif (strpos($agent, 'unix') !== false){
	        $os = 'Unix';
	    }elseif (strpos($agent, 'sun') !== false && strpos($agent, 'os') !== false){
	        $os = 'SunOS';
	    }elseif (strpos($agent, 'ibm') !== false && strpos($agent, 'os') !== false){
	        $os = 'IBM OS/2';
	    }elseif (strpos($agent, 'mac') !== false){
	        $os = 'Mac';
	    }elseif (strpos($agent, 'powerpc') !== false){
	        $os = 'PowerPC';
	    }elseif (strpos($agent, 'aix') !== false){
	        $os = 'AIX';
	    }elseif (strpos($agent, 'hpux') !== false){
	        $os = 'HPUX';
	    }elseif (strpos($agent, 'netbsd') !== false){
	        $os = 'NetBSD';
	    }elseif (strpos($agent, 'bsd') !== false){
	        $os = 'BSD';
	    }elseif (strpos($agent, 'osf1') !== false){
	        $os = 'OSF1';
	    }elseif (strpos($agent, 'irix') !== false){
	        $os = 'IRIX';
	    }elseif (strpos($agent, 'freebsd') !== false){
	        $os = 'FreeBSD';
	    }elseif (strpos($agent, 'teleport') !== false){
	        $os = 'teleport';
	    }elseif (strpos($agent, 'flashget') !== false){
	        $os = 'flashget';
	    }elseif (strpos($agent, 'webzip') !== false){
	        $os = 'webzip';
	    }elseif (strpos($agent, 'offline') !== false){
	        $os = 'offline';
	    }else{
	        $os = '未知操作系统';
	    }
	    return $os;
	}
}

/**
 *获取浏览器版本
 *
 *@return array
 */
if ( ! function_exists('getBrowser'))
{
	function getBrowser()
	{
		if (empty($_SERVER['HTTP_USER_AGENT'])){
			return '';
		}
		$agent       = $_SERVER['HTTP_USER_AGENT'];
		$browser     = '';
		$browser_ver = '';
		if (preg_match('/LBBROWSER/i', $agent, $regs)){
			$browser     = '猎豹浏览器';
			$browser_ver = '';
		}elseif (preg_match('/TaoBrowser\/([^\s]+)/i', $agent, $regs)){
			$browser     = '淘宝浏览器';
			$browser_ver = '';
		}elseif (preg_match('/theworld/i', $agent, $regs)){
			$browser     = '世界之窗浏览器';
			$browser_ver = '';
		}elseif (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)){
			$browser     = 'Internet Explorer';
			$browser_ver = $regs[1];
		}elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)){
			$browser     = 'FireFox';
			$browser_ver = $regs[1];
		}elseif (preg_match('/QQBrowser\/([^\s]+)/i', $agent, $regs)){
			$browser     = 'QQBrowser';
			$browser_ver = $regs[1];
		}elseif (preg_match('/BIDUBrowser\/([^\s]+)/i', $agent, $regs)){
			$browser     = 'BIDUBrowser';
			$browser_ver = $regs[1];
		}elseif (preg_match('/Maxthon/i', $agent, $regs)){
			$browser     = '(Internet Explorer ' .$browser_ver. ') Maxthon';
			$browser_ver = '';
		}elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)){
			$browser     = 'Opera';
			$browser_ver = $regs[1];
		}elseif (preg_match('/OPR[\s|\/]([^\s]+)/i', $agent, $regs)){
			$browser     = 'Opera';
			$browser_ver = $regs[1];
		}elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)){
			$browser     = 'OmniWeb';
			$browser_ver = $regs[2];
		}elseif (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)){
			$browser     = 'Chrome';
			$browser_ver = $regs[1];
		}elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)){
			$browser     = 'Netscape';
			$browser_ver = $regs[2];
		}elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs)){
			$browser     = 'Safari';
			$browser_ver = $regs[1];
		}elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)){
			$browser     = '(Internet Explorer ' .$browser_ver. ') NetCaptor';
			$browser_ver = $regs[1];
		}elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)){
			$browser     = 'Lynx';
			$browser_ver = $regs[1];
		}
		if(!empty($browser)){
			return addslashes($browser . ' ' . $browser_ver);
		}else{
			return '未知浏览器';
		}
	}
}

/**
 * 生成密码
 */
if ( ! function_exists('generatePassword'))
{
	function generatePassword($password,$ip,$time)
	{
		$password = md5(md5(md5(md5($password.$ip.$time)).$time).$time);
		return $password;
	}
}


/****************************************************
 * 微信带证书提交数据 - 微信红包使用
 ****************************************************/
if ( ! function_exists('wxHttpsRequestPem'))
{ 
   	function wxHttpsRequestPem($url, $vars, $second=30,$aHeader=array()){
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        //以下两种方式需选择一种
        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,PUBPATH.'config/cert/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,PUBPATH.'config/cert/apiclient_key.pem');
        curl_setopt($ch,CURLOPT_CAINFO,'PEM');
        curl_setopt($ch,CURLOPT_CAINFO,PUBPATH.'config/cert/rootca.pem');
        //第二种方式，两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,PUBPATH.'config/cert/all.pem');
        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else { 
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n"; 
            curl_close($ch);
            return false;
        }
    }
}


/**
 +----------------------------------------------------------
 * 将一个字符串部分字符用*替代隐藏
 +----------------------------------------------------------
 * @param string    $string   待转换的字符串
 * @param int       $bengin   起始位置，从0开始计数，当$type=4时，表示左侧保留长度
 * @param int       $len      需要转换成*的字符个数，当$type=4时，表示右侧保留长度
 * @param int       $type     转换类型：0，从左向右隐藏；1，从右向左隐藏；2，从指定字符位置分割前由右向左隐藏；3，从指定字符位置分割后由左向右隐藏；4，保留首末指定字符串
 * @param string    $glue     分割符
 +----------------------------------------------------------
 * @return string   处理后的字符串
 +----------------------------------------------------------
 */
if ( ! function_exists('hideStr'))
{
	function hideStr($string, $bengin=0, $len = 4, $type = 0, $glue = "*") {
		if (empty($string))
			return false;
		$array = array();
		if ($type == 0 || $type == 1 || $type == 4) {
			$strlen = $length = mb_strlen($string);
			while ($strlen) {
				$array[] = mb_substr($string, 0, 1, "utf8");
				$string = mb_substr($string, 1, $strlen, "utf8");
				$strlen = mb_strlen($string);
			}
		}
		if ($type == 0) {
			for ($i = $bengin; $i < ($bengin + $len); $i++) {
				if (isset($array[$i]))
					$array[$i] = "*";
			}
			$string = implode("", $array);
		}else if ($type == 1) {
			$array = array_reverse($array);
			for ($i = $bengin; $i < ($bengin + $len); $i++) {
				if (isset($array[$i]))
					$array[$i] = "*";
			}
			$string = implode("", array_reverse($array));
		}else if ($type == 2) {
			$array = explode($glue, $string);
			$array[0] = hideStr($array[0], $bengin, $len, 1);
			$string = implode($glue, $array);
		} else if ($type == 3) {
			$array = explode($glue, $string);
			$array[1] = hideStr($array[1], $bengin, $len, 0);
			$string = implode($glue, $array);
		} else if ($type == 4) {
			$left = $bengin;
			$right = $len;
			$tem = array();
			for ($i = 0; $i < ($length - $right); $i++) {
				if (isset($array[$i]))
					$tem[] = $i >= $left ? "*" : $array[$i];
			}
			$array = array_chunk(array_reverse($array), $right);
			$array = array_reverse($array[0]);
			for ($i = 0; $i < $right; $i++) {
				$tem[] = $array[$i];
			}
			$string = implode("", $tem);
		}
		return $string;
	}
}

/**
 * 检查是否微信浏览器打开
 */
if ( ! function_exists('checkWX'))
{
	function checkWX() {
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if (strpos($user_agent, 'MicroMessenger') === false) {
		    // 非微信浏览器禁止浏览
		    echo "HTTP/1.1 401 Unauthorized";
		    die;
		}
	}
}

